//! 数据库迁移
//!
//! 处理数据库模式的创建和演进。

use async_trait::async_trait;
use nacos_core::Result;

#[cfg(feature = "all-db")]
use sqlx::{Pool, any::Any};

/// 数据库迁移器trait
#[async_trait]
pub trait Migrator: Send + Sync {
    /// 应用所有待处理的迁移
    async fn up(&self) -> Result<()>;
    
    /// 回滚最新的迁移
    async fn down(&self) -> Result<()>;
    
    /// 检查迁移状态
    async fn status(&self) -> Result<()>;
}

/// 为sqlx连接池实现的通用迁移运行器
#[cfg(feature = "all-db")]
pub async fn run_migrations(pool: &Pool<Any>) -> std::result::Result<(), sqlx::migrate::MigrateError> {
    // sqlx::migrate!宏会查找项目根目录下的 "migrations" 文件夹
    // 我们需要确保这个文件夹存在并且包含SQL迁移文件
    // 例如: migrations/20240101120000_create_config_table.sql
    tracing::info!("Running database migrations...");
    // 实际使用时，请确保 migrations 目录存在于项目根目录
    sqlx::migrate!("./migrations").run(pool).await?;
    tracing::info!("Database migrations completed successfully.");
    Ok(())
}

/// 创建配置表的SQL语句 (MySQL & PostgreSQL 兼容)
pub const CREATE_CONFIG_TABLE_SQL: &str = "
CREATE TABLE IF NOT EXISTS configs (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    namespace VARCHAR(255) NOT NULL,
    group_name VARCHAR(255) NOT NULL,
    data_id VARCHAR(255) NOT NULL,
    content TEXT,
    md5 VARCHAR(32) NOT NULL,
    version BIGINT NOT NULL DEFAULT 1,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    creator VARCHAR(255),
    description VARCHAR(1024),
    UNIQUE (namespace, group_name, data_id)
);
";

/// 创建服务实例表的SQL语句 (MySQL & PostgreSQL 兼容)
pub const CREATE_SERVICE_INSTANCE_TABLE_SQL: &str = "
CREATE TABLE IF NOT EXISTS service_instances (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    instance_id VARCHAR(255) NOT NULL,
    service_name VARCHAR(255) NOT NULL,
    group_name VARCHAR(255) NOT NULL,
    namespace VARCHAR(255) NOT NULL,
    ip VARCHAR(45) NOT NULL,
    port INT NOT NULL,
    weight DOUBLE PRECISION NOT NULL,
    healthy BOOLEAN NOT NULL,
    enabled BOOLEAN NOT NULL,
    ephemeral BOOLEAN NOT NULL,
    cluster_name VARCHAR(255) NOT NULL,
    metadata TEXT,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE (namespace, group_name, service_name, instance_id)
);
";
